//index.js
//获取应用实例
const app = getApp();
const api = require("../../utils/api.js").default;
const myRequest = require("../../utils/request.js").default;

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    banner:[],
    head:"首页"
   
  },
  //事件处理函数
  bindViewTap: function() {
    
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  onReady(){
    var that=this;
    //请求主页api
    wx.request({
      url: api.index,
      success:function(res){
        console.log(res.data.data.hotGoodsList)
        that.setData({
          banner:res.data.data.banner,
          hotGoods: res.data.data.hotGoodsList,
          newGoods: res.data.data.newGoodsList

        })
      }
    });

  }
  ,
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    this.login()
  },
  login(){
    wx.request({
      url: api.loginByweixin,
      method: "POST",
      data: {
        appId: "wxeb20d2de78068940",
        secret: "1431d997fb9f8d9b322d7d1ad59eab60",
        code: app.globalData.code,
        userInfo: app.globalData.userInfo
      },
      success(res){
        //缓存
        //异步
        console.log("login",res)
        wx.setStorage({
          key: 'token',
          data: res.data.data.token,
          success: function () {
            console.log("已缓存");
            myRequest(api.index, "GET", {}, function (res) {
              console.log(res)
            });
          }
        })
      }
    })
  },
  toHotGoods(e){
    console.log(e.currentTarget.dataset)
    var goodsId = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: "/pages/induct/induct?id="+ goodsId,
    })
  },
  toNewGoods(e) {
    console.log(e.currentTarget.dataset)
    var goodsId = e.currentTarget.dataset.newgoodsid;
    wx.navigateTo({
      url: "/pages/induct/induct?id=" + goodsId,
    })
  }
})
